package main

import (
	"flag"
	"fmt"
	"github.com/google/uuid"
	"github.com/spf13/pflag"
	"github.com/spf13/viper"
	"go.uber.org/zap"
	"google.golang.org/grpc"
	"google.golang.org/grpc/health"
	"google.golang.org/grpc/health/grpc_health_v1"
	"net"
	"os"
	"os/signal"
	"shop_srvs/pkg/registry"

	"shop_srvs/order_srv/global"
	"shop_srvs/order_srv/handler"
	"shop_srvs/order_srv/ioc"
	"shop_srvs/order_srv/proto"
	"shop_srvs/order_srv/utils"
)

func main() {
	IP := flag.String("ip", "192.168.71.100", "ip地址")
	Port := flag.Int("port", 0, "端口号")

	InitConfig()
	ioc.InitLogger()
	ioc.InitDB()
	ioc.InitGoodsSrvConn()
	//initialize.InitRocketMQ()
	ioc.InitRabbitMQ()

	flag.Parse()
	zap.S().Infoln("ip...", *IP)
	if *Port == 0 {
		*Port, _ = utils.GetFreePort()
	}

	server := grpc.NewServer()
	proto.RegisterOrderServer(server, &handler.Order{})
	lis, err := net.Listen("tcp", fmt.Sprintf("%s:%d", *IP, *Port))
	if err != nil {
		panic(err)
	}

	//注册服务健康检查
	grpc_health_v1.RegisterHealthServer(server, health.NewServer())

	uid, _ := uuid.NewUUID()
	serviceID := uid.String()

	registerClient := registry.NewRegistryClient()
	err = registerClient.Registry(*IP, *Port, viper.GetString("consul.name"), viper.GetStringSlice("consul.tags"), serviceID)
	if err != nil {
		zap.S().Panic("服务注册失败:", err.Error())
	}
	zap.S().Debugf("启动服务器, 端口： %d", *Port)
	go func() {
		defer lis.Close()
		if err = server.Serve(lis); err != nil {
			panic("failed to start grpc:" + err.Error())
		}
	}()

	//监听订单超时topic
	//if err = global.Consumer.Subscribe("order_timeout", consumer.MessageSelector{},
	//	handler.OrderTimeout); err != nil {
	//	zap.S().Info("读取消息失败")
	//}
	//_ = global.Consumer.Start()

	msgs, err := global.RabbitMQ.RecieveDead()
	if err != nil {
		panic(err)
	}

	go func() {
		handler.OrderTimeout(msgs)
	}()

	//接收终止信号
	quit := make(chan os.Signal)
	signal.Notify(quit)

	<-quit
	global.RabbitMQ.Destroy()
	global.RabbitMQDead.Destroy()
	if err = registerClient.DeRegister(serviceID); err != nil {
		zap.S().Info("注销失败:", err.Error())
	} else {
		zap.S().Info("注销成功:")
	}
}
func GetEnvInfo(env string) bool {
	viper.AutomaticEnv()
	return viper.GetBool(env)
}
func InitConfig() {
	debug := GetEnvInfo("DEVELOPMENT")
	cfile := pflag.String("config",
		"order_srv/config/dev.yaml", "配置文件路径")
	pflag.Parse()

	if debug {
	}

	// 直接指定文件路径
	viper.SetConfigFile(*cfile)
	if err := viper.ReadInConfig(); err != nil {
		panic(err)
	}
}
